package com.dyh.quickdemo.demos.EnhanceFc;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;

/*
@Author=Joey Wheeler
@Date=2020/10/26 14:24
*/
public class StaticFuncEnhancer {


    public  static <T,R> Function<T,R> enhanceTimeoutFallback(final Function<T,R> core,Function<T,R> fallBack,long limitMilliseconds,ExecutorService executor){
        return t->{
            R r = null;
            try {
                Future<R> coreFuture=executor.submit(()->core.apply(t));
                r = coreFuture.get(limitMilliseconds, TimeUnit.MILLISECONDS);
            } catch (TimeoutException e) {
                r = fallBack.apply(t);
            }
            catch (Exception e){
                /**/
            }
            return r;
        };

    }

    public  static  <T,R> Function<T,R> enhanceInterceptors(final Function<T,R> core,final Function<T,R>... interceptors){
        return enhanceInterceptors(core, Arrays.asList(interceptors));
    }

    public  static  <T,R> Function<T,R> enhanceInterceptors(final Function<T,R> core,final List<Function<T,R>> interceptors){
        if (interceptors == null)
            return core;
        return t -> {
            R r = null;
            for (Function<T, R> interceptor : interceptors) {
                r = interceptor.apply(t);
                if (r!=null)//拦截到
                    return r;
            }
            r = core.apply(t);
            return r;
        };
    }


    public static void main(String[] args) {
        Function<String,String> core = s -> {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return s+"!";
        };

        Function<String,String> fuckInspector = s -> {
            if (s.contains("fuck"))
                return "冚家铲";
            return null;
        };

        //FuncEnhancer.enhanceInterceptors(core,fuckInspector);
    }
}
